package com.fenqing.leetcode.code.t0_200.t100_200;

import cn.hutool.json.JSONUtil;
import com.fenqing.annotations.Execute;
import com.fenqing.core.Topic;

/**
 * @author fenqing
 */
public class Topic167 extends Topic {
    /**
     * 构造器
     *
     * @param input1 输入
     * @param input2 输入
     */
    public Topic167(String input1, String input2) {
        super(input1, input2);
    }

    @Execute
    public int[] twoSum(int[] numbers, int target) {
        /* 方法1
        Map<Integer, Integer> map = new HashMap<>();
        int length = numbers.length;
        for (int i = 0; i < length; i++) {
            int t = target - numbers[i];
            Integer index = map.get(t);
            if(index == null){
                map.put(numbers[i], i);
            } else {
                return new int[]{index + 1, i + 1};
            }
        }
        return new int[]{};
        */
        /*//方法2
        int length = numbers.length;
        for (int i = 0; i < length; i++) {
            int t = target - numbers[i];
            int p = i + 1, q = length;
            while (p < q) {
                int m = (p + q) / 2;
                if (numbers[m] == t) {
                    return new int[]{i + 1, m + 1};
                } else if (numbers[m] < t) {
                    p = m + 1;
                } else {
                    q = m;
                }
            }
        }*/
        //方法3
        int length = numbers.length;
        int left = 0, right = length - 1;
        while (left < right) {
            int sum = numbers[left] + numbers[right];
            if (sum == target) {
                return new int[]{left + 1, right + 1};
            } else if (sum < target) {
                left++;
            } else {
                right--;
            }
        }
        return new int[]{};
    }

    public static void main(String[] args) {
        Topic167 topic = new Topic167("[2,7,11,15]", "9");
        int[] run = topic.run();
        System.out.println(JSONUtil.toJsonStr(run));
    }
}
